package controller

import (
	"encoding/json"
	"errors"
	"fmt"
	"haiqiu-go-admin/entity"
	"haiqiu-go-admin/result"
	"haiqiu-go-admin/service"
	"haiqiu-go-admin/utils"
	"log"
	"net/http"
)

func (*ConfigApi) SystemConfigHandle(w http.ResponseWriter, r *http.Request) {
	method := r.Method
	switch method {
	case http.MethodGet:
		ConfigAPI.systemConfigById(w, r)
		break
	case http.MethodPost:
		msg := fmt.Sprintf("该接口不支持%s请求", method)
		result.Fail(w, r, errors.New(msg))
		break
	case http.MethodDelete:
		msg := fmt.Sprintf("该接口不支持%s请求", method)
		result.Fail(w, r, errors.New(msg))
		break
	case http.MethodPut:
		ConfigAPI.systemConfigUpdate(w, r)
		break
	default:
		break
	}
}

// SystemConfig 查询系统配置
func (*ConfigApi) systemConfigById(w http.ResponseWriter, r *http.Request) {
	sysConfig, err := service.ConfigSelectByPrimaryKey(1)
	if err != nil {
		result.Fail(w, r, err)
		return
	}
	result.Ok(w, r, sysConfig)
}

func (*ConfigApi) systemConfigUpdate(w http.ResponseWriter, r *http.Request) {
	jsonData, err := utils.GetBodyFormatJson(w, r)
	var sysConfig = entity.SysConfig{}
	err = json.Unmarshal(jsonData, &sysConfig)
	lastId, err := service.SystemConfigUpdate(&sysConfig)
	if err != nil {
		result.Fail(w, r, err)
		return
	}
	result.Ok(w, r, lastId)
}

func (*ConfigApi) UploadTheme(w http.ResponseWriter, r *http.Request) {
	data, err := service.UploadTheme(w, r)
	if err != nil {
		log.Println(err.Error())
		result.Fail(w, r, err)
		return
	}
	result.Ok(w, r, data)
}
